//
//  NoticeViewController.swift
//  BellManage
//
//  Created by Bestsch on 16/3/31.
//  Copyright © 2016年 wsl. All rights reserved.
//

import UIKit

class NoticeViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {
    
    var segmentedControl: UISegmentedControl!
    var tableView: UITableView!
    
    var mark = "1"
    
    var workArray = NSMutableArray()
    var classArray = NSMutableArray()
    var teacherArray = NSMutableArray()
    
    let top = 10
    var pageIndex = 1
    
    var modetype: String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        self.title = "班级通知"
    
        //1207 - 铃铛管家去除右上角发送通知按钮
//        #if EDUMANAGE

//            self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "add"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(NoticeViewController.addclick))
//        #endif
        InitViews()
    }
    func InitViews(){
        
        let array = ["班级通知","班级排行","教师排行"]
        segmentedControl = UISegmentedControl.init(items: array)
        segmentedControl.frame = CGRect(x: 30, y: 74, width: screenW - 60, height: 40)
        segmentedControl.selectedSegmentIndex = 0
        segmentedControl.tintColor = barColor
        segmentedControl.addTarget(self, action: #selector(ClassWorkViewController.selTab), for: UIControlEvents.valueChanged)
        self.view.addSubview(segmentedControl)
        
        
        tableView = UITableView.init(frame: CGRect(x: 0, y: segmentedControl.frame.maxY + 10, width: screenW, height: screenH - segmentedControl.frame.maxY - 10))
        tableView.backgroundColor = UIColor.init(hexString: "f6f6f6", alpha: 1)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        self.view.addSubview(tableView)
        setUpRefresh()
        
    }
    
    func setUpRefresh() {
        if mark == "1" {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(NoticeViewController.refresh))
            tableView.footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(NoticeViewController.loadMore))
            self.tableView.header.beginRefreshing()
        }else {
            tableView.header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(NoticeViewController.refresh))
            tableView.footer = nil
            self.tableView.header.beginRefreshing()
        }
        
    }
    /**
     加载更多
     */
    func loadMore() {
        
        if (reachability?.isReachable())! {
            let user = getUserPojo()
            let url = server + adminwebapppi
            pageIndex += 1
            let page: String = String(pageIndex)
            let request = requestHeader + "8</t><sch>" + user.schid + "</sch><top>5</top><pagindex>" + page + "</pagindex></channel></rss>"
            
            //+++++++++++++++++++ 1208 加载更多、刷选除去全校通知
//            let tempArray = getData(url, request: request) as [AnyObject]
//            print("\(tempArray)")
//
//            for i in 0...tempArray.count-1 {
//                let tempDic = tempArray[i] as! JSON
//                let type = tempDic["types"].stringValue
//                //type = 7 说明是校级通知
//                if type != "7" {
//                    workArray.add(tempArray[i])
//                }
//            }
            //+++++++++++++++++++
            workArray.addObjects(from: getData(url, request: request) as [AnyObject])
            //++++++++
            
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }
 
        tableView.footer.endRefreshing()
    }
    /**
     刷新数据
     t=8   全校班级通知
     XmlNode schseridxml = ndoc.SelectSingleNode("//rss/channel/sch");
     XmlNode topxml = ndoc.SelectSingleNode("//rss/channel/top");
     XmlNode pagcountxml = ndoc.SelectSingleNode("//rss/channel/pagindex");
     */
    func refresh() {
        
        if (reachability?.isReachable())! {
            
            let user = getUserPojo()
            let url = server + adminwebapppi
            /**
             *  mark == "1" 班级通知
             *  mark == "2" 班级排行
             *  mark == "3" 教师排行
             */
            if mark == "1" {
                pageIndex = 1
                let page: String = String(pageIndex)
                let request = requestHeader + "8</t><sch>" + user.schid + "</sch><top>6</top><pagindex>" + page + "</pagindex></channel></rss>"
                
                //++++++++++++++++ 1208 删除全校通知、====== 1230 桐乡教育删除全校通知 ====
//                let tempArray = getData(url, request: request)
//                workArray.removeAllObjects()
//                
//                for i in 0...tempArray.count-1 {
//                    let tempDic = tempArray[i] as! JSON
//                    let type = tempDic["types"].stringValue
//                    
//                    //type = 7 说明是校级通知
//                    if type != "7" {
//                        workArray.add(tempArray[i])
//                    }
//                }
                //++++++++++++++++
                workArray = getData(url, request: request)
                //++++++++
                tableView.separatorStyle = UITableViewCellSeparatorStyle.none
            }else if mark == "2" {
                let request = requestHeader + "9</t><sch>" + user.schid + "</sch></channel></rss>"
                
                classArray =  getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
            }else if mark == "3" {
                let request = requestHeader + "10</t><sch>" + user.schid + "</sch></channel></rss>"
                
                teacherArray =  getData(url, request: request)
                tableView.separatorStyle = UITableViewCellSeparatorStyle.singleLine
            }
            tableView.reloadData()
            
        } else {
            HYLog("网络连接：不可用")
        }
        
        
        
        tableView.header.endRefreshing()
    }
    /**
     选项切换
     */
    func selTab() {
        let n = segmentedControl.selectedSegmentIndex
        switch n {
        case 0:
            mark = "1"
            setUpRefresh()
            break
        case 1:
            mark = "2"
            setUpRefresh()
            break
        case 2:
            mark = "3"
            setUpRefresh()
            break
        default:
            break
        }
    }
    
    /**
     高度
     
     - parameter tableView: tableview
     - parameter indexPath: item
     
     - returns: 高度
     */
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if mark == "1" {
            
            return 130
        }else if mark == "2" {
            return 60
        }else {
            return 60
        }
    }
    /**
     多少行
     
     - parameter tableView: tableview
     - parameter section:
     
     - returns: 行数
     */
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if mark == "1" {
            return workArray.count
        }else if mark == "2" {
            return classArray.count
        }else {
            return teacherArray.count
        }
        
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if mark == "1" {
            
            if (indexPath as NSIndexPath).row < workArray.count {
                let cellIdentifier = "NoticeTableViewCellIdentifier";
                let dic = workArray[indexPath.row] as! JSON
                let cell = NoticeTableViewCell(dictionary: dic, reuseIdentifier: cellIdentifier)
                cell.deleImage.isHidden = true
                cell.selectionStyle = UITableViewCellSelectionStyle.none;
                return cell
            }else {
                return UITableViewCell()
            }
            
            
        }else if mark == "2" {
            let cellIdentifier = "ClassSendTableViewCellIdentifier";
            
            let cell: ClassSendTableViewCell = ClassSendTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < classArray.count {
                
                let dic = classArray[indexPath.row] as! JSON
                let classname = dic["classname"].stringValue
                let count = dic["classcon"].stringValue
                
                cell.classname.text = classname
                cell.count.text = "发布：" + count
                
            }
            
            return cell
            
        }else {
            let cellIdentifier = "ClassCountTableViewCellIdentifier";
            
            let cell: StudentListTableViewCell = StudentListTableViewCell.init(style: UITableViewCellStyle.default, reuseIdentifier: cellIdentifier)
            cell.selectionStyle = UITableViewCellSelectionStyle.none;
            if (indexPath as NSIndexPath).row < teacherArray.count {
                let dic = teacherArray[indexPath.row] as! JSON
                let teaname = dic["teaname"].stringValue
                let count = dic["usersendcon"].stringValue
                var photo = dic["teaphoto"].stringValue
                photo = photo.replacingOccurrences(of: "../..", with: "").replacingOccurrences(of: "../", with: "/view/")
                photo = server + photo
                cell.userTx.sd_setImage(with: URL.init(string: photo), placeholderImage: UIImage.init(named: "touxiangm"))
                cell.userName.text = teaname
                cell.count.text = "发布：" + count
            }
            
            return cell
            
        }
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if mark == "1" {
            let dic = workArray[indexPath.row] as! JSON
            let contentVC = NoticeContentViewController()
            contentVC.dic = dic
            self.navigationController?.pushViewController(contentVC, animated: true)
        }
    }
    
    func addclick(){
        let add = AddnoticeViewController()
        add.modetype = modetype
        self.navigationController?.pushViewController(add, animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
     // Get the new view controller using segue.destinationViewController.
     // Pass the selected object to the new view controller.
     }
     */
    
}
